import {GameVar} from "../game/GameVar";
import {StatEvent, Statistic} from "../../statistic/statistic";
import {utils} from "../utils/utils";

declare const sharedCanvas;
declare const wx;
const SDWMiniSDK = require("./sdw/SDWMiniSDK");

class WxUtils {
  isWechat = false;
  private sdk: any;
  private appId = "2022090955";

  constructor() {
    this.isWechat = cc.sys.platform === cc.sys.WECHAT_GAME;
  }

  login(callback: Function) {
    if (!this.isWechat) {
      callback(utils.parseQuery("appid=2022090955&channel=10000&uid=1839698333&openid=oxbtr5fZbXnpyRreoMH5GHw5Kp70&time=1535534793&sign=964132a860c65268a819b5f29fe130b2"))
      return;
    }
    const wxAppId = 'wxaa1c3f3a2ae4d000'//夏日
    // const wxAppId = 'wxd290b7f814787b2c'// 欢乐
    this.sdk = new SDWMiniSDK({
      wxAppId: wxAppId,     // 微信小游戏的APPID
      channel: "10000",   // 平台给予的平台ID，默认
      appId: this.appId,      // 闪电玩平台的appid
      useSdw: true,         // 是否在H5版本中自动注入sdw，dhpay文件
    });
    this.sdk.getAuthInfo({
      success: (res) => {
        const {appid, uid, openid, time, sign, nick} = res;
        GameVar.userInfo = res;
        const channel = this.sdk.getChannel();
        callback({appid, channel, uid, openid, time, sign})
      },
      fail: function (res) {
        callback(res)
      }
    });
  }

  public getHeadTexture(sprite: cc.Sprite) {
    if (this.isWechat) {
      const image = wx.createImage()
      image.onload = function () {
        let texture = new cc.Texture2D();
        texture.initWithElement(image);
        texture.handleLoadedTexture();
        sprite.spriteFrame = new cc.SpriteFrame(texture);
      }
      image.src = GameVar.userInfo.avatarUrl;
    }
    return null;
  }

  getChannel() {
    if (this.sdk) {
      return this.sdk.getChannel();
    }
    return null
  }

  getSharedCanvas() {
    if (!this.isWechat) {
      return document.createElement('canvas');
    }
    return sharedCanvas;
  }

  postMessage(data: any) {
    if (!this.isWechat) {
      return;
    }
    wx.postMessage(data)
  }

  showLoading(data: any) {
    if (!this.isWechat) {
      return;
    }
    wx.showLoading(data);
  }

  hideLoading() {
    if (!this.isWechat) {
      return;
    }
    wx.hideLoading();
  }

  getQuery() {
    if (this.isWechat) {
      const options = wx.getLaunchOptionsSync()
      return this.formatToQuery(options.query);
    }
    return '';
  }

  formatToQuery(params: Object) {
    let array = [];
    for (let key in params) {
      array.push(key + '=' + params[key])
    }
    return array.join('&')
  }

  async shareToFriends() {
    if (!this.isWechat) {
      return;
    }
    const share = await this.getShareInfo();
    Statistic.emit(StatEvent.BTNSHARE)
    try {
      return await this.shareAppMessage(share.title, share.img)
    } catch (e) {
      return null
    }
  }

  createGameClubButton(param) {
    if (this.isWechat) {
      return wx.createGameClubButton(param);
    }
  }

  private shareAppMessage(title: string, imgUrl: string): Promise {
    return new Promise((resolve, reject) => {
      this.sdk.onSetShareOperate({
        title: title,
        imageUrl: imgUrl,
        query: wxUtils.formatToQuery({inviteId: GameVar.userInfo.uid, inviteArea: 1}),
        fastShare: true,    // 是否快速转发，false表示设置
        success: res => resolve(res),
        fail: res => reject(res)
      });
    })
  }

  private async getShareInfo() {
    const info = await this.getShareInfos();
    const config = info.share;
    return config[Math.floor(Math.random() * config.length)];
  }

  async setShareInfo() {
    if (!this.isWechat) {
      return;
    }
    const share = await this.getShareInfo()
    wx.showShareMenu({withShareTicket: true})

    const self = this;

    function onShare(title, imageUrl) {
      self.sdk.onSetShareOperate({
        title,
        imageUrl,
        fastShare: false
      });
    }

    onShare(share.title, share.img)
  }

  private shareInfo: any;

  private getShareInfos() {
    return new Promise((resolve, reject) => {
      if (this.shareInfo) {
        return resolve(this.shareInfo)
      }
      this.sdk.getSdwAdInfo({
        id: this.appId,   // 广告ID，没有特定广告ID，则填写游戏APPID（是闪电玩的平台ID哦）
        success: (res) => {
          this.shareInfo = res;
          resolve(res)
        },
        fail: function (res) {
          reject(res)
        }
      });
    })
  }

  /**
   * 视频广告
   * @returns {Promise<boolean>}
   */
  showVideoAd(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (!this.isWechat) {
        return resolve(false)
      }
      let videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-cf3170fd31a774ad'
      })
      videoAd.onClose((res: any) => {
        resolve(res.isEnded)
      })
      videoAd.load()
        .then(() => videoAd.show())
        .catch(err => reject(err))
    })
  }

  onShow(callback: Function) {
    if (wxUtils.isWechat) {
      wx.onShow(callback)
    } else {
      callback()
    }
  }

  offShow(callback: Function) {
    if (wxUtils.isWechat) {
      wx.offShow(callback)
    }
  }

  private menuAd = null

  /**
   * 广告
   * @returns {Promise<void>}
   */
  async showMenuAd() {
    if (!wxUtils.isWechat) {
      return
    }
    const sysInfo = await this.getSysInfo()
    if (!this.menuAd) {
      this.menuAd = wx.createBannerAd({
        adUnitId: 'adunit-3737bfb4cdac89ec',
        style: {
          left: sysInfo.screenWidth / 2 + 10,
          top: -40,
          width: 280,
          height: 20
        }
      });
    }
    this.menuAd.show().then(() => {
      this.menuAd.style.left = sysInfo.screenWidth / 2 + 10
      if (this.menuAd.style.realHeight < 100) {
        this.menuAd.style.top = -20
      } else {
        this.menuAd.style.top = -40
      }
    })
  }

  /**
   * 广告
   * @returns {Promise<void>}
   */
  async showReviveAd() {
    if (!wxUtils.isWechat) {
      return
    }
    const sysInfo = await this.getSysInfo();
    this.menuAd.show().then(() => {
      this.menuAd.style.left = sysInfo.screenWidth / 2 - this.menuAd.style.realWidth / 2;
      this.menuAd.style.top = sysInfo.screenHeight - this.menuAd.style.realHeight
    })
  }

  hideMenuAd() {
    if (this.menuAd) {
      this.menuAd.hide()
    }
  }

  private sysInfo: any;

  getSysInfo() {
    return new Promise((resolve, reject) => {
      if (this.sysInfo) {
        return resolve(this.sysInfo)
      }
      wx.getSystemInfo({
        success: res => {
          this.sysInfo = res
          resolve(res)
        },
        fail: reject
      })
    })
  }

  reAuth(info) {
    this.sdk.reAuth(info)
  }

  toSdk() {
    if (!wxUtils.isWechat) {
      return;
    }
    this.sdk.goToSdw();
  }

  pay(payData: any, options: { success: Function, fail: Function, complete?: Function }) {
    if (!this.isWechat) {
      return;
    }
    payData.gameName = '夏日大作战';
    payData.nick = GameVar.userInfo.nick;
    payData.areaName = '一区';
    payData.zoneId = '1';

    payData.success = options.success;
    payData.fail = options.fail;
    this.sdk.chooseSDWPay(payData, {}, false, true);
  }
}

export const wxUtils = new WxUtils();

class WxAd {

  private adMap = new Map();

  showVideo(adUnitId: VideoAd) {
    return new Promise(resolve => {
      this.getVideoAd(adUnitId).then(videoAd => {
        videoAd.show();
        videoAd.onClose((res: any) => {
          resolve(res.isEnded)
        })
      });
    })
  }

  async showBanner(adUnitId: BannerAd) {
    const bannerAd: any = this.getBannerAd(adUnitId);
    bannerAd.show().then(async () => {
      const sysInfo = await this.getSysInfo();

    })
  }

  private setBannerAdPosition(bannerAd: any, sysInfo) {
    switch (bannerAd.adUnitId) {
      case BannerAd.MENU:
        bannerAd.style.left = sysInfo.screenWidth / 2 + 10
        if (bannerAd.style.realHeight < 100) {
          bannerAd.style.top = -20
        } else {
          bannerAd.style.top = -40
        }
        break;
      default:
        bannerAd.style.left = sysInfo.screenWidth / 2 - bannerAd.style.realWidth / 2;
        bannerAd.style.top = sysInfo.screenHeight - bannerAd.style.realHeight
        break;
    }
  }

  private sysInfo: any;

  private getSysInfo() {
    return new Promise((resolve, reject) => {
      if (this.sysInfo) {
        return resolve(this.sysInfo)
      }
      wx.getSystemInfo({
        success: res => {
          this.sysInfo = res
          resolve(res)
        },
        fail: reject
      })
    })
  }

  private getVideoAd(adUnitId: VideoAd) {
    return new Promise((resolve, reject) => {
      if (this.adMap.get(adUnitId)) {
        resolve(this.adMap.get(adUnitId))
      } else {
        let videoAd = wx.createRewardedVideoAd({
          adUnitId,
        });
        videoAd.load()
          .then(() => {
            this.adMap.set(adUnitId, videoAd);
            resolve(videoAd)
          })
          .catch(err => reject(err))
      }
    })
  }

  private getBannerAd(adUnitId: BannerAd) {
    return new Promise((resolve, reject) => {
      if (this.adMap.get(adUnitId)) {
        resolve(this.adMap.get(adUnitId))
      } else {
        let bannerAd = wx.createBannerAd({
          adUnitId,
          width: 280,
          height: 20
        })
        this.adMap.set(adUnitId, bannerAd);
        resolve(bannerAd)
      }
    })
  }
}

enum BannerAd {
  INFI = 'adunit-2106b8360787f3b7',
  LIMIT = 'adunit-63fe880d68642e7f',
  FIGHT_OVER = 'adunit-68c13ccb010b9216',
  MENU = 'adunit-3737bfb4cdac89ec'
}

enum VideoAd {
  LUCKY = 'adunit-06660ba7a2462c9c',
  REVIVE = 'adunit-cf3170fd31a774ad'
}